package com.apexedu.portal.service.impl;

import com.apexedu.framework.service.impl.AbstractBaseServiceSupport;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.Pager;
import com.apexedu.framework.util.SeqFactory;
import com.apexedu.portal.action.PwdFindAction;
import com.apexedu.portal.entity.TPwdQ;
import com.apexedu.portal.util.DBMUtil;
import com.apexedu.util.StringUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 密码找回问题设置
 * Created by ly on 2015/5/15.
 */

@Service("pwdFindService")
public class PwdFindServiceImpl extends AbstractBaseServiceSupport {
    @Override
    public <T> List<T> list(Object myaction, Pager pager) throws Exception {
        PwdFindAction action = (PwdFindAction) myaction;
        String sqlColumn = "select a.wid,a.type,a.title,a.state,a.orderno," +
                "(select case when count(*)>0 then 1 else 0 end from t_pwd_a b where b.qid=a.wid) as answer";
        String sql = " from t_pwd_q a where 1=1";
        TPwdQ pwdQ = action.getPwdQ();
        List<String> listParm = new ArrayList<String>();
        if (null != pwdQ) {
            if (StringUtil.isNotBlank(pwdQ.getTitle())) {
                sql += " and instr(a.title,?)>0";
                listParm.add(pwdQ.getTitle());
            }
            if (StringUtil.isNotBlank(pwdQ.getState())) {
                sql += " and a.state = ?";
                listParm.add(pwdQ.getState());
            }
            if (StringUtil.isNotBlank(pwdQ.getType())) {
                sql += " and instr(a.type,?)>0";
                listParm.add(pwdQ.getType());
            }
        }
        long c = DBUtil.count(sql, listParm.toArray());
        pager.setTotalRows(c);
        List list = DBUtil.queryPageBeanList(pager, sqlColumn + sql + " order by orderno,wid desc",
                TPwdQ.class, listParm.toArray());
        return list;
    }

    @Override
    public boolean remove(Object myaction) throws Exception {
        return false;
    }

    @Override
    public void load(Object myaction) throws Exception {
        PwdFindAction action = (PwdFindAction) myaction;
        String wid = action.getWid();
        TPwdQ pwdQ = baseDao.findById(TPwdQ.class, wid);
        action.setPwdQ(pwdQ);
    }

    @Override
    public void saveOrUpdate(Object myaction) throws Exception {
        PwdFindAction action = (PwdFindAction) myaction;
        TPwdQ pwdQ = action.getPwdQ();
        if (StringUtil.isBlank(pwdQ.getWid())) {
            pwdQ.setWid(SeqFactory.getNewSequenceAlone());
            baseDao.save(pwdQ);
        } else {
            baseDao.updateNotNull(pwdQ);
        }
    }
}
